var menuId;
var gridStore;
var grid;
Ext.onReady(function(){
	Ext.QuickTips.init();
	gridStore = Ext.create("Ext.data.Store",{
        proxy:{
            type:'ajax',  
            url:'/permission/showPermissionByMenuId',
            reader:{  
                type:'json',  
                totalProperty:'total',  
                root:'data',  
                idProperty:'id'  
            }  
        },  
        fields:[
           {name:'permission_id'}, //mapping:0 这样的可以指定列显示的位置，0代表第1列，可以随意设置列显示的位置  
           {name:'permission_name'},
           {name:'kind'},
           {name:'value'},
           {name:'create_time'},
           {name:'update_time'},
           {name:'description'}
        ]  
    });
	
	var store = Ext.create('Ext.data.TreeStore', { 
		autoLoad : true,
		proxy : {
             type : 'ajax',
             url : '/menu/showMenuByConf',
             reader : {
                 type : 'json',
                 root : 'children'//数据  
             }, 
             //传参  
             extraParams : {  
                 id : 'null'  
             }
         },
	     root : {
	         text : '管理菜单',
	         expanded : true 
	     },
	     listeners : {
	         'beforeexpand' : function(node,eOpts){  
	        	 //点击父亲节点的菜单会将节点的id通过ajax请求，将到后台  
	             this.proxy.extraParams.id = node.raw.id;
	         }  
	     }  
	});
	
	var tree = Ext.create("Ext.tree.Panel", {
		region		: 'west',
		title		: '菜单',
		width		: 300,
		store		: store,
		lines		: false,
		useArrows	: true,
		rootVisible	: false,
		collapsible : true, // 是否折叠
		split 		: true
	});
	
	tree.expandAll();//展开所有节点
    //tree.collapseAll(); //关闭所有节点
	tree.on('itemclick', function(view,record){
		menuId = record.raw.menu_id;
		gridStore.load({params:{menuId:menuId}}); 
	});
	
    var columns = [
       {xtype: 'rownumberer'},
       {header:'编号',dataIndex:'permission_id',hidden: true},
       {header:'权限名称',dataIndex:'permission_name',width:'20%'},
       {header:'权限ID',dataIndex:'kind',width:'15%'},
       {header:'权限状态',dataIndex:'value',width:'10%',renderer:function(value){
           if(value=='true'){
               return "<span style='color:red;font-weight:bold';>禁用</span>";  
           } else {
               return "<span style='color:green;font-weight:bold';>正常</span>";  
           }
		}},
	   {header:'描述',dataIndex:'description',width:'18%'},
       {header:'创建时间',dataIndex:'create_time',renderer:function(value){
    	   return formatDateTime(value);
       },width:'18%'},
       {header:'最后更新时间',dataIndex:'update_time',renderer:function(value){
    	   return formatDateTime(value);
       },width:'18%'}
   ];
    var sm = Ext.create('Ext.selection.CheckboxModel');
    grid = Ext.create("Ext.grid.Panel",{
    	region: 'center',
    	title:	'权限',
    	border: false,
    	selModel: sm,
    	store: gridStore,
        columns: columns,
        region: 'center', //框架中显示位置，单独运行可去掉此段
        loadMask:true, //显示遮罩和提示功能,即加载Loading……  
        forceFit:true, //自动填满表格  
        columnLines:false, //列的边框
        rowLines:true, //设置为false则取消行的框线样式
        dockedItems: [{
        	xtype:'toolbar',
        	dock:'top',
        	displayInfo: true,
        	items:[
        	       { xtype:'button',id:'addPermission',text: '增加权限',iconCls:'Useradd',hidden:true,listeners: {click:function(){addPermission();}}},
        	       { xtype:'button',id:'editPermission', text: '编辑权限',disabled:true,iconCls:'Useredit',hidden:true,listeners: {click:function(){updatePermission();}}},
        	       { xtype:'button',id:'delPermission', text: '删除权限',disabled:true,iconCls:'Userdelete',hidden:true,listeners: {click:function(){delPermission();}}},
        	       '->',
    	    	   {id:'searchPermissionInput',xtype: 'combo',name: 'name',fieldLabel: '权限名称(联想输入，自动检索)',hidden:true,
        	    	   labelAlign:'left',labelWidth:200,
        	    	   store:gridStore, 
    	    		   hideTrigger:true,
    	    		   displayField: 'permission_name',
    	               valueField: 'permission_name',
    	               queryMode:"local",
    	               editable:true,
    	               triggerAction:"all"},
                   {id:'searchAllPermission',xtype: 'button', text: '显示全部',iconCls:'Zoom',hidden:true,listeners:{click:function(){gridStore.load({params:{menuId:menuId}}); }}}
        	 ]
        }]
    });
    // 表格配置结束
    
    grid.getView().on('render', function(view) {
        view.tip = Ext.create('Ext.tip.ToolTip', {
            // 所有的目标元素
            target: view.el,
            // 每个网格行导致其自己单独的显示和隐藏。
            delegate: view.itemSelector,
            // 在行上移动不能隐藏提示框
            trackMouse: true,
            // 立即呈现，tip.body可参照show前。
            renderTo: Ext.getBody(),
            //自定义的样式
            //baseCls:"tip-body",
            height:30,
            listeners: {
                // 当元素被显示时动态改变内容.
                beforeshow: function updateTipBody(tip) {
                    tip.update('描述： "' + view.getRecord(tip.triggerElement).get('description') + '"');
                }
            }
        });
    });
    
    //监听表格
    grid.getSelectionModel().on({
        selectionchange: function(sm, selections) {
            if (selections.length) {
            	Ext.getCmp('editPermission').setDisabled(false);
            	Ext.getCmp('delPermission').setDisabled(false);
            } else {
            	Ext.getCmp('editPermission').setDisabled(true);
            	Ext.getCmp('delPermission').setDisabled(true);
            }
        }
    });
    
    //表格右键菜单  
    var contextmenu = new Ext.menu.Menu({  
        id:'theContextMenu',  
        items:[{
        	id:'rightAddPermission',
            text:'增加权限',
            iconCls:'Useradd',
            hidden:true,
            handler:function(){  
            	addPermission();  
            }  
        },'-',{
        	id:'rightEditPermission',
            text:'编辑权限',
            iconCls:'Useredit',
            hidden:true,
            handler:function(){  
            	updatePermission();
            }  
        },'-',{
        	id:'rightDelPermission',
            text:'删除权限',
            iconCls:'Userdelete',
            hidden:true,
            handler:function(){
            	delPermission();
            }  
        },'-',{
        	id:'rightRefresh',
            text:'刷新',
            iconCls:'Arrowrefreshsmall',
            hidden:true,
            handler:function(){
            	gridStore.load({params:{menuId:menuId}}); 
            }  
        }]  
    });  
    
    grid.on("itemcontextmenu",function(view,record,item,index,e){  
        e.preventDefault();  
        contextmenu.showAt(e.getXY());  
    });
    
    grid.on("itemdblclick",function(grid, row){
    	updatePermission(); 
    });
    
    grid.on("afterRender",function(){
	Ext.Ajax.request({
        url: '/menuPer/getMenuPer',
        timeout: 30000,
      	success: function(response,options) {
      		var respText = Ext.JSON.decode(response.responseText);
      		if(respText.code == 'OK') {
      			var rec = respText.data;
      			for(var i=0; i<rec.length; i++){
      				if(rec[i].kind=='addPermission'){
      					var addUserV = rec[i].value;
      					//按钮不能使用.hidden=true;
      					if(addUserV =='true'){
      						Ext.getCmp('addPermission').hide();
      					}else{
      						Ext.getCmp('addPermission').show();
      					}
      				}
      				if(rec[i].kind=='editPermission'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('editPermission').hide();
      					}else{
      						Ext.getCmp('editPermission').show();
      					}
      				}
      				if(rec[i].kind=='delPermission'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('delPermission').hide();
      					}else{
      						Ext.getCmp('delPermission').show();
      					}
      				}
      				if(rec[i].kind=='searchPermissionInput'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('searchPermissionInput').hide();
      					}else{
      						Ext.getCmp('searchPermissionInput').show();
      					}
      				}
      				if(rec[i].kind=='searchAllPermission'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('searchAllPermission').hide();
      					}else{
      						Ext.getCmp('searchAllPermission').show();
      					}
      				}
      				if(rec[i].kind=='rightAddPermission'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('rightAddPermission').hide();
      					}else{
      						Ext.getCmp('rightAddPermission').show();
      					}
      				}
      				if(rec[i].kind=='rightEditPermission'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('rightEditPermission').hidden=true;
      					}else{
      						Ext.getCmp('rightEditPermission').hidden=false;
      					}
      				}
      				if(rec[i].kind=='rightDelPermission'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('rightDelPermission').hidden=true;
      					}else{
      						Ext.getCmp('rightDelPermission').hidden=false;
      					}
      				}
      				if(rec[i].kind=='rightRefresh'){
      					var addUserV = rec[i].value;
      					if(addUserV =='true'){
      						Ext.getCmp('rightRefresh').hidden=true;
      					}else{
      						Ext.getCmp('rightRefresh').hidden=false;
      					}
      				}
      			}
      		}
      	},
      	failure: function(response,options) {}
      });
    });
    
	// 整体架构容器
	Ext.create("Ext.container.Viewport", {
		layout : 'border',
		id     : 'winView',
		border: false,
		items : [tree,grid]
	});
});